package site.xuxingcan.httpinputmethod;

import android.content.Intent;

import java.util.HashMap;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * Created by xuxingcan on 16-7-28.
 */
public class HttpGetServerInboundHandler extends ChannelInboundHandlerAdapter {
    private static final String FALSE = "false", TRUE = "true", TEXT = "text", KEY = "key";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            String uri = request.uri();
            String result = FALSE;
            if (uri.length() > 2 && uri.contains("?")) {
                String par = uri.substring(uri.indexOf("?") + 1, uri.length());
                String[] keyValues = par.split("&");
                HashMap<String, String> hashMap = new HashMap<>();
                for (String keyValue : keyValues) {
                    String[] s = keyValue.split("=");
                    if (s.length == 2) {
                        hashMap.put(s[0], s[1]);
                    }
                }
                if (hashMap.containsKey(TEXT) && MyApplication.mContext != null) {
                    Intent intent = new Intent();
                    intent.putExtra(WifiInputMethod.TEXT, hashMap.get(TEXT));
                    intent.setAction(WifiInputMethod.TEXT_ACTION);
                    MyApplication.mContext.sendBroadcast(intent);
                    result = TRUE;
                }
            }
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, Unpooled.wrappedBuffer(result.getBytes("UTF-8")));
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            ctx.write(response);
            ctx.flush();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
